<?php

namespace app\common\service;

use app\common\exception\BusinessException;
use PHPMailer\PHPMailer\Exception;
use think\facade\Cache;
use think\facade\Config;

class VerifyService
{
    /**
     * 验证有效期
     * @var int
     */
    protected $ttl = 3600;

    /**
     * 读取配置
     * @param $tplId
     * @return array|mixed
     * @throws BusinessException
     */
    protected function getConfig(string $tplId): array
    {
        $config = Config::get('tpl.api')[$tplId] ?? [];
        if (!$config)
        {
            throw new BusinessException('TPL模板配置读取失败');
        }
        return $config;
    }

    /**
     * 发送
     * @param $key
     * @param $code
     * @param $tplId
     * @throws BusinessException
     * @throws Exception
     */
    public function send(string $key, string $code, string $tplId)
    {
        //send
        $config = $this->getConfig($tplId);
        send_email($key, $config['title'], $config['content']);

        //cache
        $prefix = Config::get('mcp.cache_key.mail_code');
        if (!Cache::set($prefix . $key, $code, $this->ttl))
        {
            throw new BusinessException('验证码Cache储存异常');
        }
    }

    /**
     * 验证
     * @param string $key
     * @param string $code
     * @return bool
     */
    public function check(string $key, string $code): bool
    {
        //cache
        $prefix = Config::get('mcp.cache_key.mail_code');

        //getCode
        $key = $prefix . $key;
        $sendCode = Cache::get($key);
        if ($sendCode == $code)
        {
            return true;
        }
        return false;
    }
}